//
//  SettingViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/27.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "UserInfoViewController.h"
#import "FeedBackViewController.h"
#import "ForgetPswViewController.h"
#import "AboutUsViewController.h"
#import "BindAlipayViewController.h"
#import "TT_WebviewController.h"

#import "SettingViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <AlipaySDK/AlipaySDK.h>


@interface SettingViewController ()

@property (weak, nonatomic) IBOutlet UIView *personalInfoControl;
@property (weak, nonatomic) IBOutlet UIView *changePhoneNumControl;
@property (weak, nonatomic) IBOutlet UIView *bindWechatControl;
@property (weak, nonatomic) IBOutlet UIView *bindAlipayControl;
@property (weak, nonatomic) IBOutlet UIView *changePswControl;
@property (weak, nonatomic) IBOutlet UIView *aboutUsControl;
@property (weak, nonatomic) IBOutlet UIView *feedBackControl;
@property (weak, nonatomic) IBOutlet UIView *clearMemoryControl;
@property (weak, nonatomic) IBOutlet UIView *logoutControl;


@property (weak, nonatomic) IBOutlet UILabel *wxBindLab;

@property (weak, nonatomic) IBOutlet UILabel *aliBindLab;
@property (weak, nonatomic) IBOutlet UIView *deallocControl;

@end

@implementation SettingViewController

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"BA_marryOauth" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxAuthCallBackAction) name:@"BA_marryOauth" object:nil];

    [self request_checkBindWXAli];
    [self initView];
}

- (void)initView {
    
    self.title = @"设置";
    self.view.backgroundColor = UIColorHex(0xf7f7f7);

    WEAKSELF
    [self.personalInfoControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        UserInfoViewController *vc = [[UserInfoViewController alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    [self.changePhoneNumControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
    }];
    
    [self.bindWechatControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {

        [weakSelf selBindWithType:SelPayMethodType_wechat];
    }];
    
    [self.bindAlipayControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        [weakSelf selBindWithType:SelPayMethodType_alipay];

    }];
    
    [self.changePswControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        ForgetPswViewController *vc = [[ForgetPswViewController alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    [self.aboutUsControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        AboutUsViewController *vc = [[AboutUsViewController alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    [self.feedBackControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        FeedBackViewController *vc = [[FeedBackViewController alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    [self.clearMemoryControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        [weakSelf cleanWebCach];
    }];
    
    [self.logoutControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        [[TTUserModel sharedObject] logOut];
        [weakSelf.navigationController popToRootViewControllerAnimated:NO];
        [[TT_TabbarViewController shareTabbar] setCurrentIndex:TT_TabbarIndexType_Home];
        
    }];
    [self.deallocControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        [weakSelf deallocUser];
    }];
}

- (void)deallocUser {
    WK(weakSelf)
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"账号注销提醒" message:@"账号注销无法恢复，请谨慎操作\n将清空个人所有账号信息！" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *go = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [[TTUserModel sharedObject] logOut];
        [weakSelf.navigationController popToRootViewControllerAnimated:NO];
        [[TT_TabbarViewController shareTabbar] setCurrentIndex:TT_TabbarIndexType_Home];
    }];
    [alertController addAction:cancle];
    [alertController addAction:go];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)selBindWithType:(SelPayMethodType)type {
    
        switch (type) {
            case SelPayMethodType_wechat:{
                [self bindWechatAction];
            } break;
            case SelPayMethodType_alipay:{
                [self bindAliAction];
            } break;
            default:
                break;
        }
}

- (void)bindWechatAction {
    if (![WXApi isWXAppInstalled]) {
        [Utilities showToast:@"手机未安装微信"];
        return;
    }
    //构造SendAuthReq结构体
    SendAuthReq* req = [[SendAuthReq alloc]init];
    req.scope = S.scope_weixin;
    req.state = S.state_weixin;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req completion:nil];
}

- (void)bindAliAction {

    WEAKSELF
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//    UIAlertAction *bindWithDrawAction = [UIAlertAction actionWithTitle:@"提现绑定"
//                                             style:UIAlertActionStyleDefault
//                                           handler:^(UIAlertAction *action) {
//                                               // do destructive stuff here
    BindAlipayViewController *vc = [[BindAlipayViewController alloc] init];
    [weakSelf.navigationController pushViewController:vc animated:YES];
    [vc setRefresh:^{
        [weakSelf request_checkBindWXAli];
    }];
//    }];
    
//    UIAlertAction *bingLoginAction = [UIAlertAction actionWithTitle:@"登录绑定"
//                                           style:UIAlertActionStyleDefault
//                                         handler:^(UIAlertAction *action) {
//                                             // do something here
//        [weakSelf request_AliInfoStr];
//    }];
//
//    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消"
//                                           style:UIAlertActionStyleCancel
//                                         handler:^(UIAlertAction *action) {
//
//    }];
//
//    [alertController addAction:bindWithDrawAction];
//    [alertController addAction:bingLoginAction];
//    [alertController addAction:cancleAction];
//    [alertController setModalPresentationStyle:UIModalPresentationPopover];
//    [self presentViewController:alertController animated:YES completion:nil];

}

//微信回调
- (void)wxAuthCallBackAction {
    NSString *code = [Utilities getFromNSUserDefaults:@"BA_marryOauth"];
    [self request_thirdAuthWithType:SelPayMethodType_wechat code:code];
}

#pragma mark 支付宝拿到authcode  微信拿到code后请求这个接口，获取openId
- (void)request_thirdAuthWithType:(SelPayMethodType)type code:(NSString *)code{
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:code forKey:@"code"];
    [dic setValue:@"2" forKey:@"sourceType"];

    switch (type) {
        case SelPayMethodType_wechat:{
            [dic setValue:@"wx" forKey:@"type"];
        } break;
        case SelPayMethodType_alipay:{
            [dic setValue:@"ali" forKey:@"type"];
        } break;
        default:
            break;
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Platform,API_ThirdAuth];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                switch (type) {
                    case SelPayMethodType_wechat:{
                        [weakSelf request_bindWithType:type OpenId:[resultDic valueForKey:@"openid"]];
                    } break;
                    case SelPayMethodType_alipay:{
                        [weakSelf request_bindWithType:type OpenId:[resultDic valueForKey:@"aliId"]];
                    } break;
                    default:
                        break;
                }
                
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {

        [SVProgressHUD showErrorWithStatus:@"请求异常"];
        [SVProgressHUD dismissWithDelay:1];
    }];
}

- (void)request_bindWithType:(SelPayMethodType)type OpenId:(NSString *)openId {
            
    NSMutableDictionary *dic = @{}.mutableCopy;

    switch (type) {
        case SelPayMethodType_wechat:{
            [dic setValue:@"wx" forKey:@"bindType"];
            [dic setValue:openId forKey:@"openid"];
            
        } break;
        case SelPayMethodType_alipay:{
            [dic setValue:@"ali" forKey:@"bindType"];
            [dic setValue:openId forKey:@"aliId"];

        } break;
        default:
            break;
    }
    
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_BindWXAli];

    [SVProgressHUD showWithStatus:@"正在绑定"];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                [weakSelf request_checkBindWXAli];
                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];

            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

#pragma mark 检查微信支付宝绑定
/*
 （未绑定，点击绑定）
 已绑定：（已绑定，如需更改可重新点击绑定）
 */
- (void)request_checkBindWXAli {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CheckWXAliBind];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSString *aliIsBind = [resultDic valueForKey:@"aliIsBind"];
                NSString *wxIsBind = [resultDic valueForKey:@"wxIsBind"];
                
                if ([aliIsBind isKindOfClass:[NSString class]] && [aliIsBind isEqualToString:@"1"]) {
                    weakSelf.aliBindLab.text = @"（已绑定，如需更改可重新点击绑定）";
                } else {
                    weakSelf.aliBindLab.text = @"（未绑定，点击绑定）";
                }
                
                if ([wxIsBind isKindOfClass:[NSString class]] && [wxIsBind isEqualToString:@"1"]) {
                    weakSelf.wxBindLab.text = @"（已绑定，如需更改可重新点击绑定）";
                } else {
                    weakSelf.wxBindLab.text = @"（未绑定，点击绑定）";
                }

            } else {
                weakSelf.wxBindLab.text = @"";
                weakSelf.aliBindLab.text = @"";
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        weakSelf.wxBindLab.text = @"";
        weakSelf.aliBindLab.text = @"";
        [SVProgressHUD dismiss];
    }];
    
}

#pragma mark 请求阿里授权str
- (void)request_AliInfoStr {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Platform,API_AliAuthStr];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                NSString *authInfo = [resultDic valueForKey:@"authInfo"];
                NSString *appScheme = @"com.ahrykj.Weddingg";
                [[AlipaySDK defaultService] auth_V2WithInfo:authInfo fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                        
                    NSString *result = [resultDic valueForKey:@"result"];
                    NSDictionary *dic = [Utilities getUrlParam:result];
                    NSString *auth_code = [dic valueForKey:@"auth_code"];
                    [weakSelf request_thirdAuthWithType:SelPayMethodType_alipay code:auth_code];

                }];
                
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"请求异常"];
        [SVProgressHUD dismissWithDelay:1];
    }];
}

//清空web缓存
- (void)cleanWebCach {
    NSArray * types =@[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache]; // 9.0之后才有的
    NSSet *websiteDataTypes = [NSSet setWithArray:types];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{

        [SVProgressHUD showSuccessWithStatus:@"缓存已清空"];
        [SVProgressHUD dismissWithDelay:1];
    }];
}

@end
